#include <string.h>

#include "libpbd.h"
#include "pbd_pblock.h"
#include "pbd_error.h"
#include "version.h"

pbd_handle_t *libpbd_init(char *device)
{
	pbd_handle_t *handle;

	// alloc memory
	handle = (pbd_handle_t *)alloc_pbd_mem(sizeof(pbd_handle_t));
	if (!handle)
		return NULL;

	if(device)
		memcpy(handle->dev, device, sizeof(device));

	// init pblock_head
	handle->pblock_head.layer = -1;	// smallest
	handle->pblock_head.clen = 0;
	handle->pblock_head.len = 0;
	handle->pblock_head.next = NULL;
	handle->pblock_head.prev = NULL;
	handle->pblock_head.id = -1;

	return handle;
}

int libpbd_destroy(pbd_handle_t *handle)
{
	pbd_pblock_t *pblock;

	if(handle->dev)
		free_pbd_mem((void *)handle->dev);

	// modify, can not provide internal infomation about pblock struct
	PBLOCK_ITER(&handle->pblock_head, pblock) {
		pbd_print(PBD_LOG_DEBUG, PBD_FUN, "Remove Pblock [layer, id]: [%d, %d]\n", pblock->layer, pblock->id);
		pbd_pblock_rem_itr(&handle->pblock_head, pblock);
	}

	free_pbd_mem((void *)handle);
	pbd_print(PBD_LOG_DEBUG, PBD_FUN, "Libpbd destroy\n");

	return 1;
}

char *libpbd_to_packet(pbd_handle_t *handle, int *size)
{
	if(!handle)
		return NULL;

	return pbd_pblock_gather(&handle->pblock_head, size);
}

void pbd_show_version()
{
	pbd_print(PBD_LOG_INFO, PBD_FUN, "Libpbd Version: %s\n", PBD_VERSION);
}

